// 云函数入口文件
const cloud = require('wx-server-sdk')

//requset包
const request = require('request')

cloud.init()


//获取timestamp方法
//--------------------------------------------
function getTimeStamp() {
  let now = Date.parse(new Date()) + ''
  return now.substr(0, now.length - 3)
}
//获取nonce_str方法
//--------------------------------------------
//获取指定区间范围随机数，包括lowerValue和upperValue
function randomFrom(lowerValue, upperValue) {
  return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
}
//生成随机字符串
function getNonceStr() {
  let chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  let str = "";
  for (let i = 0; i < 32; i++) {
    str += chars.substr(randomFrom(0, chars.length - 1), 1)
  }
  return str;
}
//sha加密
//--------------------------------------------
function encodeUTF8(s) {
  var i, r = [], c, x;
  for (i = 0; i < s.length; i++)
    if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
    else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
    else {
      if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
        c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
          r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
      else r.push(0xE0 + (c >> 12 & 0xF));
      r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    };
  return r;
};

// SHA1  
function add(x, y) {
  return ((x & 0x7FFFFFFF) + (y & 0x7FFFFFFF)) ^ (x & 0x80000000) ^ (y & 0x80000000);
}

function SHA1hex(num) {
  var sHEXChars = "0123456789abcdef";
  var str = "";
  for (var j = 7; j >= 0; j--)
    str += sHEXChars.charAt((num >> (j * 4)) & 0x0F);
  return str;
}

function AlignSHA1(sIn) {
  var nblk = ((sIn.length + 8) >> 6) + 1,
    blks = new Array(nblk * 16);
  for (var i = 0; i < nblk * 16; i++) blks[i] = 0;
  for (i = 0; i < sIn.length; i++)
    blks[i >> 2] |= sIn.charCodeAt(i) << (24 - (i & 3) * 8);
  blks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);
  blks[nblk * 16 - 1] = sIn.length * 8;
  return blks;
}

function rol(num, cnt) {
  return (num << cnt) | (num >>> (32 - cnt));
}

function ft(t, b, c, d) {
  if (t < 20) return (b & c) | ((~b) & d);
  if (t < 40) return b ^ c ^ d;
  if (t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

function kt(t) {
  return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
    (t < 60) ? -1894007588 : -899497514;
}

function SHA1(sIn) {
  var x = AlignSHA1(sIn);
  var w = new Array(80);
  var a = 1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d = 271733878;
  var e = -1009589776;
  for (var i = 0; i < x.length; i += 16) {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;
    for (var j = 0; j < 80; j++) {
      if (j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
      t = add(add(rol(a, 5), ft(j, b, c, d)), add(add(e, w[j]), kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }
    a = add(a, olda);
    b = add(b, oldb);
    c = add(c, oldc);
    d = add(d, oldd);
    e = add(e, olde);
  }
  SHA1Value = SHA1hex(a) + SHA1hex(b) + SHA1hex(c) + SHA1hex(d) + SHA1hex(e);
  return SHA1Value.toUpperCase();
}

function SHA2(sIn) {
  return SHA1(sIn).toLowerCase();
}  

function arraySortToString(str) {
  var strArr = str.split(',');
  var s1 = Array.prototype.sort.call(strArr, function (a, b) {
    for (var i = 0; i < a.length; i++) {
      if (a.charCodeAt(i) == b.charCodeAt(i)) continue;
      return a.charCodeAt(i) - b.charCodeAt(i);
    }
  });
  var result=''
  for (var m = 0; m < s1.length;m++){
    result=result+s1[m]
  }
  return result
}




// 云函数入口函数
exports.main = async (event, context) => {

  let card_id = event.card_id

  let timestamp = getTimeStamp();

  let nonce_str = getNonceStr();

  let ticketPromise = await cloud.callFunction({
    name: 'getPublicTicket'
  })
  let api_ticket = ticketPromise.result;

  let combine = timestamp + ',' + nonce_str + ',' + api_ticket + ',' + card_id

  let signature = SHA2(arraySortToString(combine));

  return {
    timestamp: timestamp,
    nonce_str: nonce_str,
    api_ticket: api_ticket,
    signature: signature
  }

}

